﻿using System;
using System.Linq;
using System.Windows;
using System.Windows.Media;

namespace DynamicGeometry
{
    public class PointOnFigure : FreePoint, IPoint
    {
        public string c_store_id { get; set; }
        public string c_guid { get; set; }

        public string c_type { get; set; }
        public bool c_is_modify { get; set; }

        public override void ReadXml(System.Xml.Linq.XElement element)
        {
            Parameter = element.ReadDouble("Parameter");
            Recalculate();
        }

        public override void WriteXml(System.Xml.XmlWriter writer)
        {
            writer.WriteAttributeString("Parameter", Parameter.ToStringInvariant());
        }

        protected override System.Windows.Shapes.Shape CreateShape()
        {
            var result = Factory.CreateDependentPointShape();
            result.Fill = new SolidColorBrush(Color.FromArgb(255, 128, 255, 128));
            return result;
        }

        public double Parameter { get; set; }

        public ILinearFigure LinearFigure
        {
            get
            {
                return (ILinearFigure)Dependencies.First();
            }
        }

        public override void MoveToCore(Point newPosition)
        {
            ILinearFigure figure = LinearFigure;
            Parameter = figure.GetNearestParameterFromPoint(newPosition);
            newPosition = figure.GetPointFromParameter(Parameter);
            base.MoveToCore(newPosition);
        }

        public override void Recalculate()
        {
            if (!Dependencies.Exists())
            {
                Exists = false;
                return;
            }
            var figure1 = LinearFigure;
            Point p = figure1.GetPointFromParameter(Parameter);
            if (!p.Exists() || LinearFigure.HitTest(p) == null)
            {
                Exists = false;
                return;
            }

            Exists = true;
            Coordinates = p;
        }
    }
}

